package com.xbongbong.paas.service.workflow.setting.impl;

import com.alibaba.fastjson.JSON;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.config.enums.WorkflowTriggerMethodEnum;
import com.xbongbong.paas.field.FilterConditionsPoJo;
import com.xbongbong.paas.pojo.workflow.NodeCoreConfigurationPojo;
import com.xbongbong.paas.pojo.workflow.WorkflowNodeTreePojo;
import com.xbongbong.paas.pojo.workflow.nodes.vo.WorkflowNodeGetVO;
import com.xbongbong.paas.pojo.workflow.settings.WorkflowGetPojo;
import com.xbongbong.paas.pojo.workflow.settings.vo.WorkflowEnableVO;
import com.xbongbong.paas.service.workflow.setting.AbstractWorkflowNodeSettings;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.util.WorkflowNodeUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.workflow.TriggerEventTypeEnum;
import com.xbongbong.workflow.domain.entity.WorkflowEntity;
import com.xbongbong.workflow.domain.entity.WorkflowNodeEntity;
import com.xbongbong.workflow.domain.entity.ext.WorkflowNodeEntityExt;
import com.xbongbong.workflow.enums.WorkflowNodeTypeEnum;
import com.xbongbong.workflow.model.WorkflowModel;
import com.xbongbong.workflow.pojo.nodes.FormTriggerNode;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/05/21 14:35
 */
@Service("workflowNodeStartSettings")
public class WorkflowNodeStartSettings extends AbstractWorkflowNodeSettings {

    @Resource
    private WorkflowModel workflowModel;

    private static String CONSTANT = "constant.workflowNode.form_trigger_node_content";

    private static final Logger LOGGER = LoggerFactory.getLogger(WorkflowNodeStartSettings.class);

    @Override
    public Integer type() {
        return WorkflowNodeTypeEnum.START_NODE.getType();
    }

    @Override
    public WorkflowNodeTreePojo getContent(WorkflowNodeEntity workflowNodeEntity, WorkflowGetPojo workflowGetPojo) throws XbbException {
        WorkflowNodeTreePojo workflowNodeTreePojo = new WorkflowNodeTreePojo();
        try {
            String formName = getFormName(workflowGetPojo, workflowNodeEntity);
            FormTriggerNode formTriggerNode = JSON.parseObject(workflowNodeEntity.getConfigData(), FormTriggerNode.class);
            if (formTriggerNode == null || formTriggerNode.getType() == null) {
                return new WorkflowNodeTreePojo();
            }
            String memo = TriggerEventTypeEnum.getMemoByType(formTriggerNode.getType());
            String content = String.format(I18nMessageUtil.getMessage(CONSTANT), formName, memo);
            List<String> list = new ArrayList<>();
            list.add(content);
            workflowNodeTreePojo.setContent(list);
        } catch (Exception e) {
            LOGGER.error("workflowNodeStartSettings.getContent error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return workflowNodeTreePojo;
    }


    @Override
    public WorkflowNodeGetVO get(WorkflowNodeEntity workflowNodeEntity) throws XbbException {
        try {
            WorkflowEntity workflowEntity = workflowModel.getByKey(workflowNodeEntity.getWorkflowId(), workflowNodeEntity.getCorpid());
            FormTriggerNode formTriggerNode = JSON.parseObject(workflowNodeEntity.getConfigData(), FormTriggerNode.class);

            addFieldPermission(workflowNodeEntity, formTriggerNode.getFieldPermission());

            NodeCoreConfigurationPojo nodeCoreConfigurationPojo = new NodeCoreConfigurationPojo();
            List<FilterConditionsPoJo> triggerConditions = formTriggerNode.getTriggerConditions();
            triggerConditions = triggerConditions == null ? new ArrayList<>() : triggerConditions;
            formTriggerNode.setTriggerConditions(triggerConditions);
            nodeCoreConfigurationPojo.setFormTriggerNode(formTriggerNode);

            WorkflowNodeGetVO workflowGetVO = new WorkflowNodeGetVO(workflowNodeEntity.getAppId(), workflowNodeEntity.getFormId(), workflowNodeEntity.getMenuId(), workflowNodeEntity.getSaasMark(), workflowNodeEntity.getBusinessType(),
                    workflowNodeEntity.getUid(), workflowNodeEntity.getId(), workflowNodeEntity.getPrevId(), workflowNodeEntity.getWrapperId(), nodeCoreConfigurationPojo);
            workflowGetVO.setUsePermission(workflowEntity.getUsePermission());

            return workflowGetVO;
        } catch (Exception e) {
            LOGGER.error("workflowNodeStartSettings.get error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public WorkflowEnableVO check(WorkflowNodeEntity workflowNodeEntity, Map<Long, WorkflowNodeEntity> nodeMap, WorkflowGetPojo workflowGetPojo) throws XbbException {
        WorkflowEnableVO workflowEnableVO = new WorkflowEnableVO();
        FormTriggerNode formTriggerNode = JSON.parseObject(workflowNodeEntity.getConfigData(), FormTriggerNode.class);
        if (Objects.equals(workflowNodeEntity.getTriggerType(), WorkflowTriggerMethodEnum.FORM.getType())) {
            if (Objects.isNull(formTriggerNode.getType())) {
                workflowEnableVO.setSuccess(0);
                workflowEnableVO.setWorkflowNodeId(workflowNodeEntity.getId());
                return workflowEnableVO;
            }
        }
//        Set<Long> formIdSet = nodeMap.values().stream().map(WorkflowNodeEntity::getFormId).filter(v -> !Objects.equals(v, 0L)).collect(Collectors.toSet());
//        if(CollectionUtils.isNotEmpty(formIdSet) && formIdSet.size() > Constant.ONE){
//            //该条工作流绑定不同表单，保存失败（首节点切换表单，可能会导致首节点和子节点绑定表单不一致的情况，操作直接拒掉）
//            throw new XbbException(ErrorCodeEnum.API_ERROR_272001,ErrorCodeEnum.API_ERROR_272001.getMsg());
//        }

        return workflowEnableVO;
    }

    @Override
    public void replaceWorkflowNodeId(WorkflowNodeEntityExt workflowNodeEntityExt, Map<Long, Long> workflowNodeMap) throws XbbException {
        FormTriggerNode formTriggerNode = JSON.parseObject(workflowNodeEntityExt.getConfigData(), FormTriggerNode.class);
        if (Objects.nonNull(formTriggerNode) && CollectionUtils.isNotEmpty(formTriggerNode.getTitleList())) {
            WorkflowNodeUtil.titleReplaceNodeId( formTriggerNode.getTitleList(), workflowNodeMap);
            workflowNodeEntityExt.setConfigData(JSON.toJSONString(formTriggerNode));
        }
    }
}

